<?php
namespace app\admin\controller;
use app\admin\model\Kf;
use think\Config;
use think\Controller;
use think\Session;

class Login extends Controller
{
    private $session_prefix = "admin";
    public function _initialize()
    {
        Session::prefix($this->session_prefix);
    }


    //登录页
    public function index()
    {
        $this->assign([
            'randToken'  => $this->createRandSession(),
        ]);
        return $this->fetch();
    }

    public function login()
    {
        $post = input('post.');
        if(!isset($post['randToken']) || !$this->chkRandSession($post['randToken']))
        {
            $this->success('token令牌错误',url('index'));
        }
        $KfModel = new Kf();
        if(!($user = $KfModel->login($post)))
        {
            $this->success('sorry，验证失败',url('index'));
        }
        else
        {
            $this->clearSession();
            $this->setCurrentUserMsg($user);
            $this->redirect(url('Index/index'));
        }

    }

    public function loginout()
    {
        $this->clearSession();
        $this->redirect(url('Login/index'));
    }

    //设置session
    public function setCurrentUserMsg($user)
    {
        session('adminId',$user['kf_id']);
        session('adminName',$user['username']);
    }

    //清空session
    public function clearSession()
    {
        session(null);
    }

    //生成随机的书写入session中
    public function createRandSession()
    {
        $token = randString(30);
        session('randToken',$token);
        return $token;
    }

    //验证随机数
    public function chkRandSession($token)
    {
        return $token == session('randToken');
    }
}